package com.example.blog.service.impl;

import com.example.blog.entity.Article;
import com.example.blog.entity.User;
import com.example.blog.mapper.ArticleMapper;
import com.example.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Article createArticle(Article article, User user) {
        article.setUser(user);
        article.setUserId(user.getId());
        article.init();
        articleMapper.insert(article);
        return article;
    }

    @Override
    public Article updateArticle(Article article) {
        Article existingArticle = findById(article.getId());
        existingArticle.setTitle(article.getTitle());
        existingArticle.setContent(article.getContent());
        existingArticle.setCoverImage(article.getCoverImage());
        existingArticle.setUpdateTime(article.getUpdateTime());
        existingArticle.setCategoryIds(article.getCategoryIds());
        articleMapper.update(existingArticle);
        return existingArticle;
    }

    @Override
    public void deleteArticle(Long id) {
        Article article = findById(id);
        articleMapper.deleteById(id);
    }

    @Override
    public Article findById(Long id) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new RuntimeException("文章不存在: " + id);
        }
        return article;
    }

    @Override
    public List<Article> findByUser(User user) {
        // 注意：需要根据实际情况调整参数，这里假设userId是user的id
        return articleMapper.selectByUserId(user.getId());
    }

    @Override
    public List<Article> findByUserId(Long userId) {
        return articleMapper.selectByUserId(userId);
    }

    @Override
    public List<Article> findAll() {
        return articleMapper.selectAllOrderByCreateTimeDesc();
    }

    @Override
    public List<Article> findAllOrderByCreateTimeDesc() {
        return findAll();
    }

    @Override
    public List<Article> searchByTitle(String keyword) {
        return articleMapper.selectByTitleContaining(keyword);
    }

    @Override
    public List<Article> findByCategoryId(Long categoryId) {
        return articleMapper.selectByCategoryId(categoryId);
    }

    @Override
    public Article increaseViewCount(Long id) {
        Article article = findById(id);
        article.setViewCount(article.getViewCount() + 1);
        articleMapper.update(article);
        return article;
    }

    @Override
    public Article increaseLikeCount(Long id) {
        articleMapper.incrementLikeCount(id);
        return findById(id);
    }

}